package com.itheima.exception;

import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

//    1.所有异常处理
    @ExceptionHandler
    public Result HandleException(Exception e) {
        log.info("出现异常了{}", e);
        return Result.error("出错了,请联系管理员");
    }

    @ExceptionHandler
    public Result HandleDuplicateKeyException(DuplicateKeyException e) {
        /*log.info("出现了SQLIntegrityConstraintViolationException异常");
        *//*
        * -- 示例1：主键重复
        Duplicate entry '1' for key 'PRIMARY'

        -- 示例2：外键不存在
        Cannot add or update a child row: a foreign key constraint fails

        -- 示例3：唯一键冲突
        Duplicate entry 'zhangsan' for key 'username'

        -- 示例4：NOT NULL 字段插入 NULL
        Column 'name' cannot be null
        * *//*
        if (e.getMessage().contains("Duplicate entry")) {
            if (e.getMessage().contains("PRIMARY")) {
                return Result.error("ID已存在");
            } else {
                String message = e.getMessage();
                int i = message.indexOf("Duplicate entry");
                String msg = message.substring(i);
                String[] s = msg.split(" ");
                Result.error(s[2]+"已存在");
            }
        }
        else if (e.getMessage().contains("a foreign key constraint fails")) {
            return Result.error("所属某个外键不存在，请检查");
        }
        else if(e.getMessage().contains("cannot be null")) {
            String message = e.getMessage();
            int i = message.indexOf("Column");
            String msg = message.substring(i);
            String[] s = msg.split(" ");
            Result.error(s[1]+"不能为空");
        }
        return Result.error("数据约束冲突：" + e.getMessage());*/
        log.error("出现异常了",e);
        String message = e.getMessage();
        int i = message.indexOf("Duplicate entry");
        String errMsg = message.substring(i);
        String[] s = errMsg.split(" ");
        return Result.error(s[2]+"已存在");
    }
}
